//
//  VoiceMainViewController.m
//  SmileRead
//
//  Created by dllo on 15/8/24.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "VoiceMainViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AsyncGETParser.h"
#import "VoiceModel.h"
#import "FileNameList.h"
#import "VoiceCell.h"
#import "Path.h"
#import "AsyncPOSTParser.h"
#import "VoiceSecondViewController.h"
#import "MJRefresh.h"
#import "MyNETLunBoTu.h"
#import "SearchViewController.h"
#import "AppDelegate.h"

@interface VoiceMainViewController ()<UITableViewDataSource, UITableViewDelegate>

{
    // 记录刷新
    NSInteger _count;
    NSInteger _i;
}

@property (nonatomic, retain) NSMutableArray *arrayOfdata;

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) UIImageView *backImage;

@property (nonatomic, retain) NSMutableArray *headerArr;


@end

@implementation VoiceMainViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrayOfdata = [NSMutableArray array];
        self.headerArr = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc
{
    [_arrayOfdata release];
    [_tableView release];
    [_backImage release];
    [_headerArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"听";
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(search)] autorelease];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self handelParser];
}

// 点击进入搜索界面
- (void)search
{
    SearchViewController *search = [[SearchViewController alloc] init];
    [search receiveArray:self.arrayOfdata ident:@"music"];
    [self.navigationController pushViewController:search animated:YES];
    [search release];
}

#if 1
- (void)receiveBsckImageName:(NSString *)imageName
{    
    
}

#endif

- (void)handelParser
{
    NSDictionary *dic = @{@"client" : @"2"};
    [AsyncPOSTParser asyncPOSTParserWithURLString:LY_Voice fileName:FILE_Voice pamarters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSMutableArray *array = [[dic objectForKey:@"data"] objectForKey:@"alllist"];
        
        
        for (int i = 0; i < array.count; i++) {
            VoiceModel *model = [[VoiceModel alloc] init];
            [model setValuesForKeysWithDictionary:array[i]];
            [self.arrayOfdata addObject:model];
            if (i % 2 == 0 && i != 0) {
                [self.headerArr addObject:model];
                if (self.headerArr.count == 3) {
                    break;
                }
            }
            [model release];
        }
        if (self.headerArr.count > 0) {
            VoiceModel *model1 = [self.headerArr lastObject];
            [self.headerArr insertObject:model1 atIndex:0];
            VoiceModel *model2 = [self.headerArr objectAtIndex:1];
            [self.headerArr addObject:model2];
        }
        
        [self createTableView];
        [self createHeaderView];
        //[self.tableView reloadData];
    }];
    
}

// 上拉加载, 下拉刷新
- (void)refresh
{
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        _i = 0;
        NSString *path = [Path pathOfLibraryWithFileName:LY_Voice];
        NSFileManager *file = [NSFileManager defaultManager];
        if ([file isExecutableFileAtPath:path]) {
            [file removeItemAtPath:path error:nil];
        }
        
        NSDictionary *dic = @{@"client" : @"2"};
        [AsyncPOSTParser asyncPOSTParserWithURLString:LY_Voice fileName:FILE_Voice pamarters:dic block:^(NSData *data) {
            
            [self.arrayOfdata removeAllObjects];
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array = [[dic objectForKey:@"data"] objectForKey:@"alllist"];
            for (int i = 0; i < array.count; i++) {
                VoiceModel *model = [[VoiceModel alloc] init];
                [model setValuesForKeysWithDictionary:array[i]];
                [self.arrayOfdata addObject:model];
                [model release];
            }
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        }];
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        // start=9&client=2&limit=9
        _count = (_i + 1) * 9;
        _i++;
        NSString *start = [NSString stringWithFormat:@"%ld", _count];
        
        NSDictionary *dic = @{@"start" : start, @"client" : @"2", @"limit" : @"9"};
        NSString *urlStr = [NSString stringWithFormat:@"%@_list", LY_Voice];
        [AsyncPOSTParser asyncPOSTParserWithURLString:urlStr fileName:FILE_Voice pamarters:dic block:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array = [[dic objectForKey:@"data"] objectForKey:@"list"];
            for (int i = 0; i < array.count; i++) {
                VoiceModel *model = [[VoiceModel alloc] init];
                [model setValuesForKeysWithDictionary:array[i]];
                [self.arrayOfdata addObject:model];
                [model release];
            }
            
            [self.tableView reloadData];
            if (data != nil) {
                [self.tableView.footer endRefreshing];
            }
        }];
        
    }];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.tableView.separatorColor = [UIColor grayColor];
    //self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self refresh];
}

- (void)createHeaderView
{
    MyNETLunBoTu *lunbo = [[[MyNETLunBoTu alloc] initWithFrame:CGRectMake(0, 180 * heightFit, self.view.frame.size.width, 250 * heightFit) arrayOfImage:self.headerArr] autorelease];
    self.tableView.tableHeaderView = lunbo;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayOfdata.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"cell";
    VoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    
    if (cell == nil) {
        cell = [[[VoiceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident] autorelease];
    }
    
    if (self.arrayOfdata.count > 0) {
        cell.model = self.arrayOfdata[indexPath.row];
        //cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150 * heightFit;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VoiceSecondViewController *second = [[VoiceSecondViewController alloc] init];
    VoiceModel *model = self.arrayOfdata[indexPath.row];
    [second receiveWithModel:model];
    [self.navigationController pushViewController:second animated:YES];
    [second release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
